<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use think\facade\Db;
use think\facade\View;
use think\exception\ValidateException;
use app\addons\File;
use app\admin\BaseController;
use app\admin\model\UserGroup;
use app\admin\validate\Catalog as CatalogValidate;
use app\admin\model\Catalog as CatalogModel;
/**
 * 分类管理
 */
class Catalog extends BaseController
{
    protected function initialize()
    {
        parent::initialize();
        $this->cacheName = 'catalog_'.$this->request->lang;
    }

    /**
     * 显示资源列表
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $input = input();
            $order = ['sort'=>'desc', 'create_time'=>'asc'];
            $data  = CatalogModel::withSearch(['keyword','language'], $input)
            ->order($order)
            ->select();
            return json(['status' => 'success', 'message' => '', 'data' => $data]);
        } else {
            $option[] = ['title' => '页面', 'name' => "page"];
            foreach (plugin_route('catalog') as $k => $catalog) {
                $catalog['name'] = $catalog['search']['type'];
                array_push($option, $catalog);
            }
            $group = UserGroup::field('id,pid,title')->where('status', 1)->select();
            View::assign([
                'option' => $option,
                'group'  => $group,
            ]);
            return View::fetch();
        }
    }

    /**
     * 保存新建的资源
     */
    public function save()
    {
        try {
            $input = input();
            validate(CatalogValidate::class)->scene('save')->check($input);
            if (! empty($input['seo_url'])) {
                $input['seo_url'] = strtolower(str_replace(' ', '-', $input['seo_url']));
                $isExist = CatalogModel::where('seo_url', $input['seo_url'])->where('language', $this->request->lang)->value('id');
                if ($isExist) {
                    return json(['status' => 'error', 'message' => '自定义地址已经存在，不可重复']);
                }
            }
            if ($input['type'] === 'page' && $input['links_type'] === 0) {
                $name = str_replace('-', '_', $input['seo_url']);
                $file = theme_path_now() . $name . '.html';
                if (! is_file($file)) {
                    File::create($file);
                }
            }
            $save = CatalogModel::create([
                'num'                 => $input['num'],
                'pid'                 => $input['pid'],
                'group_id'            => $input['group_id'],
                'title'               => $input['title'],
                'cover'               => $input['cover'],
                'field'               => $input['field'],
                'content'             => $input['content'],
                'type'                => $input['type'],
                'seo_url'             => $input['seo_url'],
                'seo_title'           => $input['seo_title'],
                'seo_keywords'        => $input['seo_keywords'],
                'seo_description'     => $input['seo_description'],
                'links_type'          => $input['links_type'],
                'links_value'         => $input['links_value'],
                'sort'                => $input['sort'],
                'create_time'         => date('Y-m-d H:i:s'),
                'language'            => $this->request->lang,
                'status'              => $input['status'],
                'show'                => $input['show'],
                'mobile'              => $input['mobile'],
            ]);
            cache($this->cacheName, NULL);
            return json(['status' => 'success', 'message' => '新增成功']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 保存更新的资源
     */
    public function update()
    {
        try {
            $input = input();
            validate(CatalogValidate::class)->check($input);
            $save  = CatalogModel::find($input['id']);
            if (! empty($input['seo_url'])) {
                $input['seo_url'] = strtolower(str_replace(' ', '-', $input['seo_url']));
                $isExist = CatalogModel::where('seo_url', $input['seo_url'])
                ->where('language', $this->request->lang)
                ->where('id', '<>', $input['id'])
                ->value('id');
                if ($isExist) {
                    return json(['status' => 'error', 'message' => '自定义地址已经存在，不可重复']);
                }
            }
            // 修改页面文件名
            $name = str_replace('-', '_', $input['seo_url']);
            $file = theme_path_now() . $name . '.html';
            if ($input['type'] === 'page' && $input['links_type'] === 0) {
                $oldName = str_replace('-', '_', $save->seo_url);
                $oldfile = theme_path_now() . $oldName . '.html';
                is_file($oldfile) ? rename($oldfile, $file) : File::create($file);
                CatalogModel::where('type','page')->where('seo_url', $save->seo_url)->update(['seo_url' => $input['seo_url']]);
            }
            $save->num                 = $input['num'];
            $save->pid                 = $input['pid'];
            $save->group_id            = $input['group_id'];
            $save->title               = $input['title'];
            $save->cover               = $input['cover'];
            $save->field               = $input['field'];
            $save->content             = $input['content'];
            $save->type                = $input['type'];
            $save->seo_url             = $input['seo_url'];
            $save->seo_title           = $input['seo_title'];
            $save->seo_keywords        = $input['seo_keywords'];
            $save->seo_description     = $input['seo_description'];
            $save->links_type          = $input['links_type'];
            $save->links_value         = $input['links_value'];
            $save->sort                = $input['sort'];
            $save->show                = $input['show'];
            $save->status              = $input['status'];
            $save->mobile              = $input['mobile'];
            $save->save();
            cache($this->cacheName, NULL);
            return json(['status' => 'success', 'message' => '修改成功']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 删除指定资源
     */
    public function delete()
    {
        try {
            $input = input();
            validate(CatalogValidate::class)->scene('delete')->check($input);
            CatalogModel::recursiveDestroy($input['ids']);
            cache($this->cacheName, NULL);
            return json(['status' => 'success', 'message' => '删除成功']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 同步主语言数据
     */
    public function synchro()
    {
        $where[] = ['language','=' ,$this->request->langDefault];
        $model = new CatalogModel;
        $data = $model::where($where)->select();
        if ($data) {
            $data    = $data->toArray();
            $saveAll = [];
            foreach ($data as $key => $val) {
                $val['language'] = $this->request->lang;
                unset($val['id']);
                array_push($saveAll, $val);
            }
            Db::startTrans();
            try {
                $model::where('language', $this->request->lang)->delete();
                $list = $model->saveAll($saveAll)->toArray();
                // 修改pid
                foreach($data as $key => $val){
                    if ($val['pid'] != 0) {
                        $parent = array_search($val['pid'],array_column($data, 'id'));
                        $pid = $list[$parent]['id'];
                        $id = $list[$key]['id'];
                        $model::where('id',$id)->update(['pid' => $pid]);
                    }
                }
                Db::commit();
                cache($this->cacheName, NULL);
                return json(['status' => 'success', 'message' => '同步成功']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 'error', 'message' => '同步失败']);
            }
        } else {
            return json(['status' => 'error', 'message' => '主语言暂无数据']);
        }
    }

    /**
     * 复制到其它语言
     */
    public function copyList() {
        if ($this->request->isPost()) {
            $input = input();
            $model = new CatalogModel;
            $saveAll = [];
            $data    = $input['rows'];
            foreach ($data as $key => $val) {
                $val['language'] = $input['language'];
                $val['pid'] = $input['catalog_id'];
                unset($val['id'],$val['children']);
                array_push($saveAll, $val);
            }
            Db::startTrans();
            try {
                $list = $model->saveAll($saveAll)->toArray();
                // 修改pid
                foreach($data as $key => $val){
                    if ($val['pid'] != 0) {
                        $parent = array_search($val['pid'],array_column($data, 'id'));
                        if ($parent !== false) {
                            $pid = $list[$parent]['id'];
                            $id = $list[$key]['id'];
                            $model::where('id',$id)->update(['pid' => $pid]);
                        }
                    }
                }
                Db::commit();
                cache('catalog_'.$input['language'], NULL);
                return json(['status' => 'success', 'message' => '复制成功']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 'error', 'message' => '复制失败']);
            }
        }
    }

    /**
     * 其它语言分类
     */
    public function copyListCatalog() {
        if ($this->request->isPost()) {
            $input = input();
            $where[] = ['language','=' ,$input['lang']];
            if (isset($input['type']) && !empty($input['type'])) {
                $where[] = ['type','=' ,$input['type']];
            }
            $order = ['sort'=>'desc', 'create_time'=>'asc'];
            $data  = CatalogModel::where($where)->order($order)->select();
            return json(['status' => 'success', 'message' => '', 'data' => $data]);
        }
    }
}